#!/usr/bin/python
# -*- encoding: utf8 =*-

import os
import urllib2
from SimpleHtmlParse import SimpleHtmlParse

#log = open("log.log", "w+")
def DetectCharset(s):
	charsets = ('gbk', 'gb18030', 'gb2312', 'iso-8859-1', 'utf-16', 'utf-8', 'utf-32', 'ascii')
	for charset in charsets:
		try:
			return unicode(s, charset)
		except:
			continue
	return s
	
class MySearchParser(SimpleHtmlParse):
	lyricArtists = []
	lyricTitles = []
	lyricUrls = []
	tags = []
	state = 0
	artist = ""
	title = ""
	url = ""
	def handle_starttag(self, tag, attrs):
		self.tags.insert(0, tag)
		if self.state == 5 and tag == "a":
			for attr in attrs:
				if attr[0] == 'href':
					self.url = attr[1]
					
	
	def handle_data(self,data):
		if self.state == 0 and data == "LRC123歌词结果":
			self.state = 2
		elif self.state == 2 and data.find("歌手:") >= 0:
			self.state = 3
		elif self.state == 3:
			self.artist += data
		elif self.state == 2 and data.find("歌曲:") >= 0:
			self.state = 4
		elif self.state == 4:
			self.title += data
		elif self.state == 2 and data.find("下载:") >= 0:
			self.state = 5
		elif self.state == 5 and data.find("LRC") >= 0:
			self.lyricTitles.append(self.title)
			self.lyricArtists.append(self.artist)
			self.lyricUrls.append("http://www.lrc123.com" + self.url)
			self.title = ''
			self.artist = ''
			self.url = ''
			self.state = 2
					
		
	
	def handle_endtag(self,tag):
		#print "</"+tag+">"
		if len(self.tags) == 0:
			return
		if self.tags[0] == tag:
			self.tags.pop(0)
		if self.state > 2 and self.tags[0] == "div":
			self.state = 2
	
	def dumpInfo(self, title, artist):
		index = 0
		for t in self.lyricTitles:
			if t.find(title) >= 0 and self.lyricArtists[index].find(artist) >= 0:
				#tmp = "作者：%s\n歌名：%s\nURL：%s\n" % (self.lyricArtists[index], t, self.lyricUrls[index])
				#print unicode(tmp, "utf8").encode("gbk")
				f = open("%d" % index, 'w+')
				f.write(DownLyric(self.lyricUrls[index]))
				f.close()
			index += 1
	def save(self, filename):
		f = open(filename, 'w+')
		f.write('<?xml version="1.0" encoding="UTF-8" ?>\n');
		index = 0
		f.write('<result>\n')
		for url in self.lyricUrls:
			f.write('\t<lrc id="%s" artist="%s" title="%s"></lrc>\n' % (self.lyricUrls[index], self.lyricArtists[index], self.lyricTitles[index]))
			index = index + 1
		f.write('</result>\n')
		f.close()

	def dumpXML(self):
		xml = '<?xml version="1.0" encoding="UTF-8" ?>\n'
		index = 0
		xml += '<result>\n'
		for url in self.lyricUrls:
			xml += '\t<lrc id="%s" artist="%s" title="%s"></lrc>\n' % (self.lyricUrls[index], self.lyricArtists[index], self.lyricTitles[index])
			index = index + 1
		xml += '</result>\n'
		return xml
        
	def dump(self):
		txt = ''
		index = 0
		for url in self.lyricUrls:
			txt += 'artist=%s\ntitle=%s\nid=%s\n' % (self.lyricArtists[index], self.lyricTitles[index], self.lyricUrls[index])
			index = index + 1
		return txt

def SearchLyric(artist, title):
	try:
	#if True:
		if len(artist) > 0:
			theurl = "http://www.lrc123.com/?keyword=%s+%s&field=all" % (title, artist)
		else:
			theurl = "http://www.lrc123.com/?keyword=%s&field=song" + title
		response = urllib2.urlopen(theurl)
		sp = MySearchParser()
		sp.feed(response.read())
		return sp.dump()
	except:
		return ""

def DownLoadLyric(ID, artist, title):
	try:
		response = urllib2.urlopen(ID)
		return response.read()
	except:
		return ""

if __name__ == '__main__':
	print SearchLyric("羽泉", "深呼吸")
	#log.close()
		
		
	
